package com.stn.zjx.givingtreasure.activity.set;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.address.AddressManagerActivity;
import com.stn.zjx.givingtreasure.activity.realauth.UserRealAuthActivity;
import com.stn.zjx.givingtreasure.activity.userprofile.ModifyUserEmailActivity;
import com.stn.zjx.givingtreasure.activity.userprofile.ModifyUserProfileActivity;
import com.stn.zjx.givingtreasure.activity.userprofile.ModifyUserQqActivity;
import com.stn.zjx.givingtreasure.activity.userprofile.ModifyUserWxActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.UpdateVersionDomain;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.ExitEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.event.UserResetPassEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.UserApi;
import com.stn.zjx.givingtreasure.net.impl.CheckVersionNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxAppTool;
import com.vondear.rxtools.RxTimeTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

public class UserSetActivity extends BaseActivity {
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.user_sex)
    ImageView userSex;
    @BindView(R.id.update_time)
    TextView updateTime;
    @BindView(R.id.email)
    TextView email;
    @BindView(R.id.qq)
    TextView qq;
    @BindView(R.id.wx)
    TextView wx;
    @BindView(R.id.realAuth)
    TextView realAuth;
    @BindView(R.id.set)
    TextView set;
    @BindView(R.id.update_tip_dot)
    View updateTipDot;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ExitEvent(ExitEvent exitEvent){
        switch (exitEvent.flag){
            case ExitEvent.SWITCH_LANGUAGE_EXIT:
                finish();
                break;
        }
    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.account_setting));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_set);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.exit_login, R.id.go_email,
            R.id.go_profie,
            R.id.go_qq,
            R.id.go_wx,
            R.id.go_real_auth,
            R.id.go_password, R.id.go_switch,
            R.id.go_relation,
            R.id.go_system_set,
       R.id.go_address_manager,
            R.id.open_er_wei_bt
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.open_er_wei_bt:
                RxActivityTool.skipActivity(this, ShowTransferErWeiActivity.class);
                break;
            case R.id.go_address_manager:
                RxActivityTool.skipActivity(this, AddressManagerActivity.class);

                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.exit_login:
           User   onlineUser=UserService.getInstance(this).getOnlineLoginUser();
                if(onlineUser!=null){
                    UserNetImpl
                            .user_exit_login(onlineUser.getToken(), "user_exit_login", new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {

                                }
                            });
                }
                if (UserService.getInstance(this)
                        .exitLogin()) {

                    RefreshEvent event=new RefreshEvent();
                    event.flag=RefreshEvent.EXIT_LOGIN_REFRESH;
                    EventBus.getDefault().post(event);
                    finish();
                } else {
                    showToast(getString(R.string.exit_login_error));
                }
                break;
            case R.id.go_email:
                RxActivityTool.skipActivity(this, ModifyUserEmailActivity.class);
                break;
            case R.id.go_qq:
                RxActivityTool.skipActivity(this, ModifyUserQqActivity.class);
                break;
            case R.id.go_wx:
                RxActivityTool.skipActivity(this, ModifyUserWxActivity.class);
                break;
            case R.id.go_profie:
                RxActivityTool.skipActivity(this, ModifyUserProfileActivity.class);
                break;
            case R.id.go_real_auth:
                RxActivityTool.skipActivity(this, UserRealAuthActivity.class);
                break;
            case R.id.go_password:
                RxActivityTool.skipActivity(this, PasswordSetActivity.class);
                break;
            case R.id.go_switch:
                RxActivityTool.skipActivity(this, LanguageSetActivity.class);
                break;
            case R.id.go_relation:
                RxActivityTool.skipActivity(this, UserRelationSetActivity.class);
                break;
            case R.id.go_system_set:
                RxActivityTool.skipActivity(this, SystemSetActivity.class);
                break;
        }
    }

    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        initUser();
        checkVersion();
    }

    public void initUser() {
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
            finish();
            return;
        }
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        UserNetImpl.user_getuserprofile_bytoken(userOnline.getToken(), userOnline.getUserId() + "user_getuserprofile_bytoken",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }
                });
    }

    //用户在服务器手机号，密码校验正确
    private void loginSuccess(UserProfileDomain domain) {
        boolean isLogin = UserService.getInstance(this)
                .login(domain.getData());
        if (!isLogin) {
            boolean isExitLogin = UserService.getInstance(this)
                    .exitLogin();
            if (isExitLogin) {
                finish();
            }
        }
    }


    //设置用户资料
    public void user_getuserprofile_bytoken(String result) {
        if (result == null) {
            return;
        }
        Gson gson = new Gson();
        UserProfileDomain domain = gson.fromJson(result.trim(), UserProfileDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                loginSuccess(domain);
                initLocationUser();
                break;
            case BaseApi.REQUEST_LOGINEXIT_ERROR_CODE:

                break;
            case BaseApi.REQUEST_TOKEN_ERROR_CODE:

                break;
        }

    }

    @SuppressLint({"SetTextI18n", "SimpleDateFormat"})
    public void initLocationUser() {
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        if (userOnline == null) {
            return;
        }
        Glide.with(this)
                .load(userOnline.getUserAvatar())
                .thumbnail(0.2f)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        avatarCiv.setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadStarted(@Nullable Drawable placeholder) {
                        super.onLoadStarted(placeholder);
                        avatarCiv.setImageResource(R.mipmap.default_avatar);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        avatarCiv.setImageResource(R.mipmap.default_avatar);
                    }
                });
        userNickname.setText(userOnline.getUserNickname());
        switch (userOnline.getUserSex()) {
            case 0:
                userSex.setVisibility(View.GONE);
                break;
            case 1:
                userSex.setVisibility(View.VISIBLE);
                userSex.setImageResource(R.mipmap.male);
                break;
            case 2:
                userSex.setVisibility(View.VISIBLE);
                userSex.setImageResource(R.mipmap.female);
                break;
        }
        Log.d(getLocalClassName(), userOnline.getUserUpdatedate() + "");
        updateTime.setText(getString(R.string.late_update_time) + ":" +
                RxTimeTool.date2String(new Date(userOnline.getUserUpdatedate()), new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")));
        email.setText(userOnline.getUserEmail());
        qq.setText(userOnline.getUserQq());
        wx.setText(userOnline.getUserWx());
        switch (userOnline.getRealStatus()) {
            case 0:
                realAuth.setText(getString(R.string.no_realauth));
                break;
            case 1:
                realAuth.setText(getString(R.string.loadng_realauth));
                break;
            case 2:
                if (!TextUtils.isEmpty(userOnline.getRealRealname())) {
                    realAuth.setText("*" + userOnline.getRealRealname().substring(1, userOnline.getRealRealname().length()));
                } else {
                    realAuth.setText("");
                }
                break;
            default:
                realAuth.setText(getString(R.string.error_realauth));
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UserResetPassEvent(UserResetPassEvent event) {
        finish();
    }


    public void checkVersion() {
        CheckVersionNetImpl.get_version(0, "get_version",
                new StringCallback() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            UpdateVersionDomain domain = new Gson().fromJson(response.body(), UpdateVersionDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    if (domain.getData() != null) {
                                        int local_code = RxAppTool.getAppVersionCode(getApplicationContext());
                                        if (local_code < domain.getData().getAppCode()) {
                                        updateTipDot.setVisibility(View.VISIBLE);
                                        }else{
                                            updateTipDot.setVisibility(View.GONE);
                                        }

                                    }else{
                                        updateTipDot.setVisibility(View.GONE);
                                    }
                                    break;
                            }
                        }

                    }
                });


    }
}
